// COS
const COS = require('cos-nodejs-sdk-v5')
const { createHash } = require('crypto')
const config = require('../../config')
const cosConfig = config.cosConfig

const cos = new COS({
  SecretId: 'AKIDkOsBIBzlS9kDTfhW6aw5zfNvFJ8i4A1d',
  SecretKey: 'Qo5A0d3GE6ugO2WlkTwGVlyAHIEyX1JV'
})

/**
 * 将 Stream 转为 Buffer
 * @param stream
 * @returns {Promise<Buffer>}
 */
function stream2buffer (stream) {
  return new Promise((resolve, reject) => {
    const _buf = []
    stream.on('data', (chunk) => _buf.push(chunk))
    stream.on('end', () => resolve(Buffer.concat(_buf)))
    stream.on('error', (err) => reject(err))
  })
}

// 上传文件到指定存储桶
async function uploadFileToBucket (bucketName, fileName, fileStream) {
  // 计算文件名
  const hash = createHash('md5')
  const fileBuffer = await stream2buffer(fileStream)
  hash.update(fileBuffer)
  const postfix = (fileName.match(/\..*$/) || [''])[0]
  const fileMd5 = hash.digest('hex')
  const md5Filename = `${fileMd5}${postfix}`
  // 上传
  const bucket = cosConfig.buckets[bucketName]
  if (!bucket) {
    throw Error(`Bucket name ${bucketName} invalid.`)
  }
  return cos.putObject({
    Bucket: bucket.Bucket,
    Region: bucket.Region,
    Key: md5Filename,
    Body: fileBuffer
  })
}

// 获取存储桶文件签名链接
async function getBucketSignedUrl (bucketName, key, expires) {
  const bucket = cosConfig.buckets[bucketName]
  if (!bucket) {
    throw Error(`Bucket name ${bucketName} invalid.`)
  }
  return cos.getObjectUrl({
    Bucket: bucket.Bucket,
    Region: bucket.Region,
    Key: key,
    Sign: true,
    Expires: expires || 3600 // 单位秒
  })
}

// 上传文件到 51talent bucket
async function uploadTo51TalentBucket (fileName, fileBuffer) {
  return await uploadFileToBucket('talent', fileName, fileBuffer)
}

// 获取 51talent 签名链接
async function get51TalentBucketSignedUrl (key, expires) {
  return getBucketSignedUrl('talent', key, expires)
}

module.exports = {
  uploadFileToBucket,
  uploadTo51TalentBucket,
  get51TalentBucketSignedUrl
}
